
/**
 * @Project : Clion_ProgrammingExercises
 * @File : 0844
 * @Author : WangRuoyu 
 * @Date : 2023/5/21 17:22
 */

#include "iostream"
#include "queue"

using namespace std;

struct node {
    int x;
    int y;
    int num;
};

int main() {
    int n, m;
    scanf("%d %d", &n, &m);
    int maze[n][m];
    bool visited[n][m];
    for (int i = 0; i < n; ++i) {
        for (int j = 0; j < m; ++j) {
            scanf("%d", &maze[i][j]);
            visited[i][j] = false;
        }
    }

    int dx[] = {0, 1, 0, -1};
    int dy[] = {1, 0, -1, 0};

    queue<node> q;
    visited[0][0] = true;
    q.push(node{0, 0, 0});
    while (!q.empty()) {
        node p = q.front();
        q.pop();
        if (p.x == n - 1 && p.y == m - 1) {
            printf("%d", p.num);
            break;
        }
        for (int i = 0; i < 4; ++i) {
            int px = p.x + dx[i];
            int py = p.y + dy[i];
            if (px >= 0 && px < n && py >= 0 && py < m && !visited[px][py] && !maze[px][py]) {
                q.push(node{px, py, p.num + 1});
                visited[px][py] = true;
            }
        }
    }

    return 0;
}